package com.hrm.controller;

import com.baidu.aip.face.AipFace;
import com.hrm.pojo.Users;
import com.hrm.service.UsersService;
import com.hrm.utils.JwtUtil;
import com.hrm.utils.entity.Result;
import com.hrm.utils.entity.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 86147
 * @Date: 2024/9/28 16:52
 * @Version: v1.0.0
 * @Description: TODO
 **/

@RestController
@RequestMapping("/face")
@Api(tags = "人脸识别")
public class FaceController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //设置APPID/AK/SK
    public static final String APP_ID = "115737617";
    public static final String API_KEY = "WBiGdwIgV2RNEpek52fTnqqD";
    public static final String SECRET_KEY = "UBxD5UuKwoSX1OAwctMKiKgXdD831by5";

    @PostMapping("/login")
    @ApiOperation(value = "人脸登录")
    public Result login(MultipartFile file) throws Exception {
        // 初始化一个AipFace
        AipFace client = null;
        try {
            client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            // 传入可选参数调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("match_threshold", "95");
            options.put("quality_control", "NORMAL");
            options.put("liveness_control", "LOW");
            //options.put("user_id", file.getOriginalFilename());
            options.put("max_user_num", "3");

            //把图片转为base64
            byte[] data = file.getBytes();
            BASE64Encoder encoder = new BASE64Encoder();
            String base64ImageStr = encoder.encode(data);

            //FACE_TOKEN
            String image = base64ImageStr;
            String imageType = "BASE64";
            String groupIdList = "test";

            // 人脸搜索
            JSONObject res = client.search(image, imageType, groupIdList, options);
            System.out.println(res.toString(2));
            //System.out.println(res.has("result"));
            JSONObject result = res.getJSONObject("result");
            System.out.println(result.toString());
            if(result == null){
                throw new Exception("认证失败，请重新验证！");
            }
            // 从user_list中获取user_id
            if (result.has("user_list") && result.getJSONArray("user_list").length() > 0) {
                //根据user_id获取用户信息,将user_id转为Integer类型
                Integer userId = Integer.parseInt(result.getJSONArray("user_list").getJSONObject(0).getString("user_id"));
                System.out.println("用户ID: " + userId); // 用户ID
                Users users = usersService.findById(userId);
                //使用用户信息生成token
                String token = jwtUtil.createJWT(users.getId() + "", users.getLoginname(), users.getStatus() + "");
                //把token存储到redis中，key为username，value为token
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token, token, 1, TimeUnit.HOURS); //设置过期时间为一小时
                return new Result(true, StatusCode.SUCCESS,"登录成功！",new String[]{token, users.getId() + "", users.getUsername(), users.getStatus() + ""});
            } else {
                throw new Exception("未找到匹配用户信息！");
            }
        }catch (Exception e){
            throw new Exception("登录失败！");
        }

    }

    @PostMapping("/reg")
    @ApiOperation(value = "人脸注册")
    public Result reg(MultipartFile file) throws Exception {
        // 初始化一个AipFace
        AipFace client = null;
        try {
            client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            // 传入可选参数调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("user_info", "user's info");
            //options.put("quality_control", "NORMAL");
            //options.put("liveness_control", "LOW");
            options.put("action_type", "REPLACE");

            //把图片转为base64
            byte[] data = file.getBytes();
            BASE64Encoder encoder = new BASE64Encoder();
            String base64ImageStr = encoder.encode(data);

            // 调用接口
            String image = base64ImageStr;
            String imageType = "BASE64";
            String groupId = "test";
//            String userId = file.getOriginalFilename();
            //获取文件名字前缀
            String userId = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            System.out.println(userId);
            // 人脸注册
            JSONObject res = client.addUser(image, imageType, groupId, userId, options);
            System.out.println(res.toString(2));
/*            if (!res.isNull("error_code")) {
                // 若存在 error_code，说明出错，返回错误信息
                return new Result(false, StatusCode.ERROR, res.getString("error_msg"), res.toString(2));
            }*/

            return new Result(true, StatusCode.SUCCESS, "注册成功!", res.toString(2));

        } catch (Exception e) {
            // 捕获异常并返回错误信息
            e.printStackTrace();


            return new Result(false, StatusCode.ERROR, "注册失败，系统异常");
        }
    }
}
